package org.linlinjava.litemall.db.service;

import static org.linlinjava.litemall.db.domain.constants.RechargeStatus.CANCEL;
import static org.linlinjava.litemall.db.domain.constants.RechargeStatus.PROCESSING;
import static org.linlinjava.litemall.db.domain.constants.RechargeStatus.SUCCESS;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import javax.annotation.Resource;
import org.linlinjava.litemall.db.dao.LitemallRechargeMapper;
import org.linlinjava.litemall.db.domain.LitemallRecharge;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class LitemallRechargeService {
  @Resource
  private LitemallRechargeMapper rechargeMapper;

  @Resource
  private LitemallAccountService accountService;

  public LitemallRecharge findById(Integer id) {
    return rechargeMapper.selectByPrimaryKey(id);
  }

  private void update(LitemallRecharge recharge) {
    rechargeMapper.updateByPrimaryKeySelective(recharge);
  }

  @Transactional
  public LitemallRecharge add(Integer accountId, BigDecimal amount) {
    LitemallRecharge recharge = new LitemallRecharge();
    recharge.setCreateTime(LocalDateTime.now());
    recharge.setUpdateTime(LocalDateTime.now());
    recharge.setAmount(amount);
    recharge.setStatus(PROCESSING);
    recharge.setAccountId(accountId);
    rechargeMapper.insertSelective(recharge);
    return recharge;
  }


  @Transactional
  public void success(Integer id, String remark) {
    LitemallRecharge recharge = findById(id);
    if (recharge.getStatus() == SUCCESS) {
      throw new RuntimeException("充值已经成功");
    }
    if (recharge.getStatus() == CANCEL) {
      throw new RuntimeException("充值已经取消");
    }
    recharge.setStatus(SUCCESS);
    recharge.setRemark(remark);
    update(recharge);

    accountService.recharge(//
        recharge.getAccountId(), remark, recharge.getId().toString(), recharge.getAmount()//
    );
  }

  @Transactional
  public void fail(Integer id, String remark) {
    LitemallRecharge recharge = findById(id);
    if (recharge.getStatus() == SUCCESS) {
      throw new RuntimeException("充值已经成功");
    }
    if (recharge.getStatus() == CANCEL) {
      throw new RuntimeException("充值已经取消");
    }
    recharge.setStatus(CANCEL);
    recharge.setRemark(remark);
    update(recharge);
  }
}
